﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.TSSC;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 中文期刊操作对象
    /// </summary>
    private TSSC_DAO tsscDAO = new TSSC_DAO();
    /// <summary>
    /// 日志操作对象
    /// </summary>
    private OperationLog_DAO operationLogDAO = new OperationLog_DAO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        String wjm = HttpUtility.UrlDecode(Request["wjm"]);
        if (null == wjm || "".Equals(wjm))
        {
            String message = "错误：参数错误";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        //指定文件名的图书手册
        TSSC_PM tsscPM = this.tsscDAO.GetTSSC_PMByWjm(wjm);

        if (null == tsscPM)
        {
            String message = "错误：没有找到该图书手册";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }

        //获取对应的分类信息
        TSSC_FL tsscFL = this.tsscDAO.GetTSSC_FLByFlbm(tsscPM.flbm);

        //设置返回按钮链接
        String flbm = (wjm.Split('-'))[0];
        this.backHyperLink.NavigateUrl = GlobalTSSC.LISTPM_PAGE + "?catalog=" + flbm;


        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;

        //分类编码
        this.flbmTextBox.Text = tsscFL.flbm;
        //分类名称
        this.flmcTextBox.Text = tsscFL.flmc;
        //索引编码
        this.sybmTextBox.Text= tsscPM.sybm;
        //出版年份
        this.cbnfTextBox.Text = tsscPM.cbnf;

        //文件名
        this.pdfHyperLink.Text = tsscPM.wjm;
        this.pdfHyperLink.NavigateUrl = GlobalResource.VIEW_PAGE + "?fileName=" + tsscPM.wjm;

        //书号
        this.shTextBox.Text = tsscPM.sh;
        //书名
        this.smTextBox.Text = tsscPM.sm;
        //出版单位
        this.cbdwTextBox.Text = tsscPM.cbdw;
        //尺寸
        this.ccTextBox.Text = tsscPM.cc.ToString();
        //页数
        this.ysTextBox.Text = tsscPM.ys.ToString();
        //封面
        this.fmCheckBox.Checked = tsscPM.fm;

        //图书来源
        this.tslyTextBox.Text = tsscPM.tsly;
        //图书简介
        this.tsjjTextBox.Text = tsscPM.tsjj;
        //图书目录
        this.tsmlTextBox.Text = tsscPM.tsml;

        this.SetPreAndNextPM();

    }

    /// <summary>
    /// 获取用户填写的图书手册篇名信息
    /// </summary>
    /// <returns></returns>
    private TSSC_PM GetTSSCPM()
    {
        TSSC_PM tsscPM = new TSSC_PM();
        //索引编码
        tsscPM.sybm = this.sybmTextBox.Text;
        //分类编码
        tsscPM.flbm = this.flbmTextBox.Text;
        //文件名
        tsscPM.wjm = this.pdfHyperLink.Text;
        //书名
        tsscPM.sm = this.smTextBox.Text.Trim();
        //图书来源
        tsscPM.tsly = this.tslyTextBox.Text.Trim();
        //出版年份
        tsscPM.cbnf = this.cbnfTextBox.Text;
        //图书简介
        tsscPM.tsjj = this.tsjjTextBox.Text;
        //图书目录
        tsscPM.tsml = this.tsmlTextBox.Text;
        //更新日期
        tsscPM.gxrq = DateTime.Now;
        //作者
        tsscPM.zz = this.zzTextBox.Text;
        //出版单位
        tsscPM.cbdw = this.cbdwTextBox.Text;
        //页数
        if (!"".Equals(this.ysTextBox.Text))
            tsscPM.ys = Int32.Parse(this.ysTextBox.Text);
        //尺寸
        if (!"".Equals(this.ccTextBox.Text))
            tsscPM.cc = (float)Double.Parse(this.ccTextBox.Text);
        //书号
        tsscPM.sh = this.shTextBox.Text;
        //封面
        tsscPM.fm = this.fmCheckBox.Checked;

        return tsscPM;

    }

    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证书名
        if (!this.ValidateSM())
        {
            return;
        }
        //验证尺寸
        if (!this.ValidateCC())
        {
            return;
        }
        //验证页数
        if (!this.ValidateYS())
        {
            return;
        }
        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }
        if (null != this.ywjmFileUpload && null != this.ywjmFileUpload.FileName && !"".Equals(this.ywjmFileUpload.FileName)) 
        {
            if (!OperationFile.Upload(this.ywjmFileUpload, this.pdfHyperLink.Text)) {
                Response.Write("<Script>alert('更新图书手册信息失败')</Script>");
                return;
            }
            
        }
        TSSC_PM tsscPM = this.GetTSSCPM();

        if (this.tsscDAO.UpdateTSSC_PM(tsscPM, ((User)Session["login"]).name))
        {
            Response.Write("<Script>alert('更新图书手册信息成功')</Script>");
            this.NextPM();
        }
        else
        {
            Response.Write("<Script>alert('更新图书手册信息失败')</Script>");
        }
    }

   /// <summary>
    /// 验证标题
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateSM()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        if(null==this.smTextBox.Text||"".Equals(this.smTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：书名不能为空";
            flag = false;
        }
        return flag;
    }

    /// <summary>验证尺寸</summary>
    private Boolean ValidateCC()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ccTextBox != null && this.ccTextBox.Text != "")
        {
            try
            {
                float val = (float)double.Parse(this.ccTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：尺寸信息不是有效数字";
                return false;
            }
        }

        return flag;
    }

    /// <summary>验证页数</summary>
    private Boolean ValidateYS()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ysTextBox != null && this.ysTextBox.Text != "")
        {
            try
            {
                int val = Int32.Parse(this.ysTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：页数信息不是有效数字";
                return false;
            }
        }

        return flag;
    }

    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
            return true;
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                }

                pdf.Close();
            }
        }
        return flag;
    }

    //全角转半角
    protected void zzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzTextBox.Text = GlobalMethod.Semicolon(this.zzTextBox.Text.Trim());
    }
    protected void cbdwTextBox_TextChanged(object sender, EventArgs e)
    {
        this.cbdwTextBox.Text = GlobalMethod.Semicolon(this.cbdwTextBox.Text.Trim());
    }

    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }

    /// <summary>
    /// 设置前一篇和后一篇的链接
    /// </summary>
    private void SetPreAndNextPM()
    {
        //上一篇
        String pre = this.GetDirectionPM(-1);
        if (null != pre)
        {
            this.preHyperLink.NavigateUrl = GlobalTSSC.EDITPM_PAGE + "?wjm=" + pre;
        }

        //下一篇
        String next = this.GetDirectionPM(1);
        if (null != next)
        {
            this.nextHyperLink.NavigateUrl = GlobalTSSC.EDITPM_PAGE + "?wjm=" + next;
        }
    }
    /// <summary>
    /// 修改下一篇
    /// </summary>
    private void NextPM()
    {
        String wjm = this.GetDirectionPM(1);
        if (null == wjm)
        {
            return;
        }
        else
        {
            Response.Redirect(GlobalTSSC.EDITPM_PAGE + "?wjm=" + wjm);
        }
    }

    /// <summary>
    /// 获取下一个文件名，不包括后缀
    /// </summary>
    /// <param name="wjm"></param>
    /// <param name="direction">大于0下一篇；反之，上一篇</param>
    /// <returns></returns>
    private String GetDirectionPM(int direction)
    {
        String result = null;
        //获取文件名的后四位流水号，并在其基础上加1
        int endIndex = this.pdfHyperLink.Text.LastIndexOf(".");

        String phString = this.pdfHyperLink.Text.Substring(endIndex - 4, 4);

        int ph = 0;

        try
        {
            ph = Int32.Parse(phString);
        }
        catch (Exception)
        {
        }

        //当前篇号+1或-1
        if (direction > 0)
        {
            ph++;
        }
        else
        {
            ph--;
        }

        phString = ph.ToString();
        //长度为1
        if (phString.Length == 1)
        {
            phString = "000" + phString;
        }
        else if (phString.Length == 2)
        {
            phString = "00" + phString;
        }
        else if (phString.Length == 3)
        {
            phString = "0" + phString;
        }

        result = this.sybmTextBox.Text + "-" + phString + ".PDF";
        TSSC_PM TSSCPM = this.tsscDAO.GetTSSC_PMByWjm(result);
        if (null == TSSCPM)
        {
            return null;
        }
        return result;
    }
}